package org.eoti.ai.genetic.ga.diploid;

import org.eoti.ai.genetic.ga.*;

import java.util.Map;
import java.util.HashMap;

/**
 * The MIT License
 * <p/>
 * Copyright (c) 2009 Malachi de AElfweald (malachid@gmail.com)
 * <p/>
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * <p/>
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 * <p/>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * Diploid cells have two homologous copies of each chromosome, usually one from the mother and one from the father. 
 * Human diploid cells have 46 chromosomes.
 */
public class DiploidGenotype<GENE>
extends Genotype<GENE>
{
	public enum Parent{Mother,Father}

	public DiploidGenotype()
	{
		super();
	}

	public Chromosome<GENE> get(Parent parent, String name )
	{
		return super.get(chromosomeName(parent, name));
	}

	public void add(Parent parent, Chromosome<GENE> chromosome)
	{
		super.add(chromosome.copy(chromosomeName(parent, chromosome.getName())));
	}

	public void add(Chromosome<GENE> chromosome)
	{
		add(Parent.Mother, chromosome);
		add(Parent.Father, chromosome);
	}

	public Map<Locus, GENE> getLoci(Parent parent, Locus ... loci)
	{
		HashMap<Locus,GENE> map = new HashMap<Locus,GENE>();
		for(Locus locus : loci)
			map.put( locus, get(parent, locus.getChromosomeName()).get(locus.getGenePosition() ));

		return map;
	}

	private String chromosomeName(Parent parent, String name)
	{
		if(name.startsWith(parent.toString())) return name;

		if(name.startsWith(Parent.Father.toString()))
			name = name.substring(Parent.Father.toString().length()+1);

		if(name.startsWith(Parent.Mother.toString()))
			name = name.substring(Parent.Mother.toString().length()+1);

		return String.format("%s:%s", parent.toString(), name);
	}
}
